"""
created@2019/11/5
"""
from .decorators import with_application
from extensions import db
from log import logger
from config.const import DataBaseConst


@with_application
def task_info_before_execute(task_id):
    """任务执行前的任务信息"""
    
    group_messages =  []
    # 查询没有父组的情况
    sql = """ select sg.wx_app_id as wx_app_id, swa.description as description,
              sg.title as group_title, sg.total_count, sm.title as msg_title
              from silo.`groups` as sg
              join silo.group_messages as sgm on sgm.group_id=sg.id
              join silo.task_has_group_messages as sthgm on sthgm.group_msg_id = sgm.id
              join silo.messages as sm on sm.id = sgm.msg_id
              join silo.silo_wx_apps as swa on swa.wx_app_id = sg.wx_app_id
              where sg.wx_app_id != 0 and sthgm.task_id = {} order by sgm.id;""".format(task_id)
    
    logger.info('\n查询任务执行前任务信息sql: \n{}'.format(sql))
    rows = db.session.execute(sql)
    for row in rows:
        item = {}
        item['wx_app_id'] = row['wx_app_id']
        item['total_count'] = row['total_count']
        item['error_count'] = 0
        item['filter_count'] = 0
        item['send_count'] = 0
        item['group_title'] = row['group_title']
        item['msg_title'] = row['msg_title']
        item['description'] = row['description']
        group_messages.append(item)

    return group_messages


@with_application
def get_openid_list(query_sql):
    """
    获取openid列表
    :param group_id: 推送对象id
    :return: openid列表
    """
    res = db.session.execute(query_sql)
    logger.info('\n获取openid列表的sql: \n{}'.format(query_sql))
    first_row = res.fetchone()
    app_id = first_row['app_id']
    openid = first_row['openid']
    openid_list = [row["openid"] for row in res]
    openid_list.append(openid)
    
    return app_id, openid_list


def task_info_after_execute(task_id):
    """执行任务后的任务信息"""
    
    sql = """select g.title as group_title,
                gm.wx_app_id as wx_app_id,
                ml.filter_count as filter_count,
                ml.total_count as total_count,
                ml.send_count as send_count,
                ml.error_count as error_count,
                m.title as msg_title,
        swa.description as description
        from group_messages as gm
        join task_has_group_messages thgm
            on thgm.group_msg_id = gm.id
        join messages as m
            on gm.msg_id = m.id
        join silo_wx_apps as swa
            on swa.wx_app_id = gm.wx_app_id
        join mass_logs ml 
            on ml.task_has_group_msg_id = thgm.id
        join groups as g 
            on g.id = gm.group_id
        where thgm.task_id = {}
        """.format(task_id)

    logger.info('\n获取一次任务的多个公众号推送反馈数据统计的sql: \n{}'.format(sql))
    rows = db.session.execute(sql)
    group_messages = []
    for row in rows:
        group_messages.append({
            'wx_app_id': row['wx_app_id'],
            'msg_title': row['msg_title'],
            'group_title': row['group_title'],
            'description': row['description'],
            'total_count': int(row['total_count']),
            'filter_count': int(row['filter_count']),
            'send_count': int(row['send_count']),
            'error_count': int(row['error_count']),
        })
    return group_messages


@with_application
def get_wx_app_info(app_id):
    
    sql = 'select app_name, wa.desc as description, origin_id, id, app_id from {}.wx_apps as wa where id= {}'.format(DataBaseConst.FOR_APIS,app_id)
    logger.info('获取单个微信公众号信息: \n{}'.format(sql))
    rows = db.session.execute(sql)
    info = {}
    # 只有一行记录
    for row in rows:
        info['app_id'] = row['app_id']
        info['app_name'] = row['app_name']
        info['origin_id'] = row['origin_id']
        info['wx_app_id'] = row['id']
        info['description'] = row['description']
    return info
